package com.hbzhit.common.utils;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.LFUCache;
import org.apache.ibatis.cache.Cache;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Mybatis缓存
 * @author DING
 */
public class MybatisCache implements Cache {

    /**
     * LFU缓存对象，参数 0,0表示数量和时间（毫秒）无限制
     */
    private final LFUCache<Object, Object> cache = CacheUtil.newLFUCache(0, 1000 * 5);

    /**
     * 读写锁
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    private final String id;

    public MybatisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object o, Object o1) {
        cache.put(o, o1);
    }

    @Override
    public Object getObject(Object o) {
        return cache.get(o);
    }

    @Override
    public Object removeObject(Object o) {
        cache.remove(0);
        return true;
    }

    @Override
    public void clear() {
        cache.clear();
    }

    @Override
    public int getSize() {
        return cache.size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}
